import { ref, reactive, onMounted, nextTick, watch, } from "vue";
import { questions } from "@/shared/types/Question";
import { useClientStore } from "../../pinia/stores/client";
import { FormRules, FormInstance } from "element-plus";

export function createQuestionsHook(props:{
    courseId: string;
    questions: Array<questions>;
  }) {


//   const props = defineProps<{
//     courseId: string;
//     questions: Array<questions>;
//   }>();
  const courseId = props.courseId || "63c0c09ae58ff204b7dcceaa";
  const client = useClientStore().client;

  const questionDialog = ref(false);
  const ruleFormRef = ref<FormInstance>();
  const questionForm = reactive({
    question: {
      question: "",
      type: "" as "选择题" | "填空题" | "简答题" | "判断题",
      selections: new Array<string>(),
      score: 0,
      questionCount: 0,
    },
    answer: {
      selections: new Array<string>(),
      // answers: new Array<Array<string>>(),
      selection: "",
    },
  });
  const rules = reactive<FormRules>({
    question: [
      {
        message: "请输入问题",
        validator: (rule, value: string, callback) => {
          if (!questionForm.question.question) {
            callback(new Error());
          } else {
            callback();
          }
        },
      },
      {
        required: true,
      },
    ],
    type: [
      {
        message: "请选择问题类型",
        validator: (rule, value: string, callback) => {
          if (!questionForm.question.type) {
            callback(new Error());
          } else {
            callback();
          }
        },
      },
    ],
    selections: [
      {
        message: "请添加选项",
        validator: (_, _2, callback) => {
          if (questionForm.question.selections.length === 0)
            callback(new Error());
          else callback();
        },
      },
    ],
    answer: [
      {
        validator: (_, _2, callback) => {
          if (questionForm.question.type === "选择题") {
            if (questionForm.answer.selections.length === 0) {
              callback(new Error("请选择答案"));
            } else {
              callback();
            }
          } else if (questionForm.question.type === "判断题") {
            if (!questionForm.answer.selection) {
              callback(new Error("请选择答案"));
            } else {
              callback();
            }
          } else {
            callback();
          }
        },
      },
    ],
  });
  const confirm = async () => {
    console.log('confirm')
    if (ruleFormRef.value) {
      try {
        await ruleFormRef.value.validate();
        const ret = await client.callApi("QuestionsSys/CreateQuestion", {
          question: {
            ...questionForm.question,
            selections:
              questionForm.question.selections.length === 0
                ? undefined
                : questionForm.question.selections,
          },
          answer: {
            selection: questionForm.answer.selection || undefined,
            selections:
              questionForm.answer.selections.length === 0
                ? undefined
                : questionForm.answer.selections,
          },
        });
        if (ret.isSucc) {
          ElMessage.success("创建成功");
          props.questions.push(ret.res.question);
          questionDialog.value = false;
          clearForm();
        }
      } catch (error) {
        console.log(error);
      }
    }
    // questionDialog.value = false
    // clearForm()
  };
  const handleClose = (done: (() => void) | undefined) => {
    ElMessageBox.confirm("Are you sure to close this dialog?")
      .then(() => {
        questionDialog.value = false;
        clearForm();
        if (done) done();
      })
      .catch(() => {
        // catch error
      });
  };
  const clearForm = () => {
    //clearForm
    questionForm.question = {
      question: "",
      type: "" as "选择题" | "填空题" | "简答题" | "判断题",
      selections: new Array<string>(),
      score: 0,
      questionCount: 0,
    };
    questionForm.answer = {
      selections: new Array<string>(),
      selection: "",
    };
  };
  const lastScore = ref(0);

  const addSelection = () => {
    questionForm.question.selections.push("");
    nextTick(() => {
      inputs.value[inputs.value.length - 1].focus();
    });
  };
  const inputBlur = (index: number) => {
    if (!questionForm.question.selections[index]) {
      questionForm.question.selections.splice(index, 1);
      return;
    }

    let count = 0;
    questionForm.question.selections.map((selection) => {
      if (selection === questionForm.question.selections[index]) count++;
      if (count >= 2) {
        ElMessage.warning("相同的选项");
        questionForm.question.selections.splice(index, 1);
        return false;
      } else {
        return true;
      }
    });

    if (
      questionForm.question.type === "判断题" &&
      questionForm.question.selections.length > 2
    ) {
      questionForm.question.selections.length = 2;
    }
  };
  const deleteSelection = (index: number) => {
    questionForm.question.selections.splice(index, 1);
  };
  const inputs = ref();
  watch(
    () => questionForm.question.type,
    (newValue) => {
      if (
        questionForm.question.type === "判断题" &&
        questionForm.question.selections.length > 2
      ) {
        questionForm.question.selections.length = 2;
      }
    }
  );

  onMounted(() => {
    // client.callApi('Get/GetQuestions',{
    // })
  });

  return {
    questionForm,
    rules,
    ruleFormRef,
    inputBlur,deleteSelection,addSelection,
    confirm,clearForm
  };
}
